package com.tzq.elastic.controller;

import com.tzq.elastic.controller.base.BaseController;
import com.tzq.elastic.dao.ArticleSearchRepository;
import com.tzq.elastic.entity.Article;
import com.tzq.elastic.entity.Author;
import com.tzq.elastic.entity.Tutorial;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.Iterator;

/**
 * @author tangzhiqiang
 * @date 2018-07-12 10:38
 */
@Api(value = "TestController", description = "测试 elastic")
@RestController
public class TestController extends BaseController {

    @Autowired
    private ArticleSearchRepository articleSearchRepository;

    @ApiOperation(value = "add", notes = "add")
    @GetMapping("/add")
    public void testSaveArticleIndex(@RequestBody Author author) {
       /* Author author = new Author();
        author.setId(1L);
        author.setName("tianshouzhi");
        author.setRemark("java developer");

        Tutorial tutorial = new Tutorial();
        tutorial.setId(1L);
        tutorial.setName("elastic search");

        Article article = new Article();
        article.setId(1L);
        article.setTitle("springboot integreate elasticsearch");
        article.setAbstracts("springboot integreate elasticsearch is very easy");
        article.setTutorial(tutorial);
        article.setAuthor(author);
        article.setContent("基于lucene elasticsearch,"
                + "基于elaticsearch spring-data-elastichsearch"
                + ",本教程将告诉您如何使用spring-data-elasticsearch对springboot进行集成");
        article.setPostTime(new Date());
        article.setClickCount(1L);*/
//        articleSearchRepository.save(article);
    }

    @ApiOperation(value = "query", notes = "query")
    @GetMapping("/query")
    public String testSearch(@RequestParam String queryString) {
        Article article = null;
        // 搜索关键字
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(queryString);
        Iterable<Article> searchResult = articleSearchRepository.search(builder);
        Iterator<Article> iterator = searchResult.iterator();
        while (iterator.hasNext()) {
            article = iterator.next();
        }
        if (article != null) {
            return success(article);
        } else {
            return success("暂无数据");
        }

    }

}
